package cn.lhn.ridersclub.service;

import cn.lhn.ridersclub.entity.Account;
import cn.lhn.ridersclub.entity.Paper;
import cn.lhn.ridersclub.entity.Support;
import cn.lhn.ridersclub.mapper.AccountMapper;
import cn.lhn.ridersclub.mapper.PaperMapper;
import cn.lhn.ridersclub.mapper.SupportMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

@Service
public class SupportServiceImpl implements SupportService {

    public SupportServiceImpl(AccountMapper accountMapper, PaperMapper paperMapper, SupportMapper supportMapper) {
        this.accountMapper = accountMapper;
        this.paperMapper = paperMapper;
        this.supportMapper = supportMapper;
    }

    private final AccountMapper accountMapper;

    private final PaperMapper paperMapper;

    private final SupportMapper supportMapper;

    @Override
    public void addSupport(Long paperId, Long accountId) {
        //  判断paper是否存在
        Paper paper = paperMapper.selectById(paperId);
        if (paper == null) {
            throw new RuntimeException("文章不存在");
        }

        //  判断账号是否存在
        Account account = accountMapper.selectById(accountId);
        if (account == null) {
            throw new RuntimeException("账号不存在");
        }

        //  判断是否存在
        QueryWrapper<Support> qw = new QueryWrapper<>();
        qw.eq("paper_id", paperId);
        qw.eq("account_id", accountId);
        Support support = supportMapper.selectOne(qw);
        if (support != null) {
            throw new RuntimeException("请勿重复操作");
        }

        //  添加数据
        int i = supportMapper.insert(new Support(0L, paperId, accountId));
        if (i == 0) {
            throw new RuntimeException("添加失败");
        }
    }

    @Override
    public void deleteSupport(Long paperId, Long accountId) {

        QueryWrapper<Support> qw = new QueryWrapper<>();
        qw.eq("paper_id", paperId);
        qw.eq("account_id", accountId);
        int i = supportMapper.delete(qw);
        if (i == 0) {
            throw new RuntimeException("删除失败");
        }
    }

    @Override
    public Boolean isSupport(Long paperId, Long accountId) {
        QueryWrapper<Support> qw = new QueryWrapper<>();
        qw.eq("paper_id", paperId);
        qw.eq("account_id", accountId);
        return supportMapper.selectOne(qw) != null;
    }

    @Override
    public Long getSupportCount(Long paperId) {
        QueryWrapper<Support> qw = new QueryWrapper<>();
        qw.eq("paper_id", paperId);
        return supportMapper.selectCount(qw);
    }
}
